package com.example.utils;

import com.example.mapper.UploadMapper;
import com.example.pojo.Source;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gdal.gdal.gdal;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class readGDB {

    @Autowired
    private UploadMapper uploadMapper;

    @Autowired
    private HttpServletRequest request;

    //声明该类自身的静态类变量
    private static readGDB readgdb;

    static {
        gdal.AllRegister();//设置gdal环境
        // 为了支持中文路径，请添加下面这句代码
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
        // 为了使属性表字段支持中文，请添加下面这句
        gdal.SetConfigOption("SHAPE_ENCODING","");
    }



    @PostConstruct
    //用 @PostConstruct 注入 bean，声明 init() 方法，进行初始化挂载；
    private void init(){
        readgdb = this;
        readgdb.uploadMapper = this.uploadMapper;
        readgdb.request = this.request;
    }

    public void GdbSource(String gdbPath) {
        Source source = new Source();
        //获取token并解析
        String jwt = readgdb.request.getHeader("token");
        Claims claims = JwtUtils.ParseJwt(jwt);
        String username = (String) claims.get("username");
        //当前登录的用户
        source.setOwner(username);
        String FileDriver = "OpenFileGDB";
        Driver driver = null;
        DataSource dataSource = null;
        driver = ogr.GetDriverByName(FileDriver);
        dataSource = driver.Open(gdbPath);
        // gdb名称
        String sourcename = StringUtils.substringAfterLast(gdbPath, "/");
        source.setSourcename(sourcename);
        int layerCount = dataSource.GetLayerCount();
        String layerName = null;
        long featureCount = 0;
        for (int i = 0; i < layerCount; i++) {
            Layer layer = dataSource.GetLayer(i);
            // 图层名称
            layerName = layer.GetName();
            System.out.println(layerName);
            source.setLayer(layerName);
            // 图层范围经纬度坐标
            double[] extent = layer.GetExtent();
            source.setBounds(Arrays.toString(extent));
            // 图层空间参考系
            SpatialReference Spatial = layer.GetSpatialRef();
            String spatialS = Spatial.toString();
            source.setCoordinatesystem(spatialS.substring(spatialS.length() - 16));
            // 图层类型
            int GeomType = layer.GetGeomType();
            String datapyte = LayerType.Typename(GeomType);
            source.setDatatype(datapyte);
            //解析Layer属性字段信息
            FeatureDefn featureDefn = layer.GetLayerDefn();
            int fieldCount = featureDefn.GetFieldCount();
            Map<String, Object> fieldMap = new HashMap<>();
            for (int j = 0; j < fieldCount; j++) {
                FieldDefn fieldDefn = featureDefn.GetFieldDefn(j);
                String fieldName = fieldDefn.GetName();
                int fieldType = fieldDefn.GetFieldType();
                String typeName = fieldDefn.GetFieldTypeName(fieldType);
                fieldMap.put(fieldName, typeName);
            }
            //字段类型信息
            source.setField(fieldMap.toString());
            //解析Layer属性表,  featureCount:每个图层的要素总数
            featureCount = layer.GetFeatureCount();
            // 每个图层的要素数量
            source.setElementcount((int) featureCount);
            //便利每个layer的要素信息
            for (int j = 0; j < featureCount; j++) {
                Feature feature = null;
                while ((feature = layer.GetNextFeature()) != null) {
                    Set<Map.Entry<String, Object>> entries = fieldMap.entrySet();
                    for (Map.Entry<String, Object> next : entries) {
                        String key = next.getKey();
                        String value = feature.GetFieldAsString(key);
                    }
                }
            }
            //当前时间
            source.setCreateTime(LocalDateTime.now());
            //使用声明的该类的静态类变量，调用 Mapper 层
            readgdb.uploadMapper.insert(source);
            log.info("sourcedata数据上传 {}", source);
        }
    }
}
